home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C & C++ Multimedia Cyber Classroom
/
C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso
/
src
/
fig15_12.jar
/
Ch15
/
Fig15_12
/
STACK
/
STACK.H
< prev
next >
Wrap
C/C++ Source or Header
|
1997-08-26
|
2KB
|
85 lines
// STACK.H
// Definition of class Stack
#ifndef STACK_H
#define STACK_H
#include <iostream.h>
#include <assert.h>
#include "stacknd.h"
template <class T>
class Stack {
public:
Stack(); // default constructor
~Stack(); // destructor
void push( T & ); // insert item in stack
T pop(); // remove item from stack
int isEmpty() const; // is the stack empty?
void print() const; // output the stack
private:
StackNode<T> *topPtr; // pointer to fist StackNode
};
// Member function definitions for class Stack
template <class T>
Stack<T>::Stack() { topPtr = 0; }
template <class T>
Stack<T>::~Stack()
{
StackNode<T> *tempPtr, *currentPtr = topPtr;
while ( currentPtr != 0 ) {
tempPtr = currentPtr;
currentPtr = currentPtr->nextPtr;
delete tempPtr;
}
}
template <class T>
void Stack<T>::push( T &d )
{
StackNode<T> *newPtr = new StackNode<T>( d, topPtr );
assert( newPtr != 0 ); // was memory allocated?
topPtr = newPtr;
}
template <class T>
T Stack<T>::pop()
{
assert( !isEmpty() );
StackNode<T> *tempPtr = topPtr;
topPtr = topPtr->nextPtr;
T poppedValue = tempPtr->data;
delete tempPtr;
return poppedValue;
}
template <class T>
int Stack<T>::isEmpty() const { return topPtr == 0; }
template <class T>
void Stack<T>::print() const
{
StackNode<T> *currentPtr = topPtr;
if ( isEmpty() ) // Stack is empty
cout << "Stack is empty" << endl;
else { // Stack is not empty
cout << "The stack is:" << endl;
while ( currentPtr != 0 ) {
cout << currentPtr->data << ' ';
currentPtr = currentPtr->nextPtr;
}
cout << endl;
}
}
#endif